package com.zc58s.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


/**
 * @author 图灵源码
 * 条件变量，条件唤醒
 */

public class ReentrantLockDemo6 {
    /**
     *
     */
    private static ReentrantLock lock = new ReentrantLock();
    /**
     *
     */
    private static Condition cigCon = lock.newCondition();
    /**
     *
     */
    private static Condition takeCon = lock.newCondition();

    private static boolean hashcig = false;
    private static boolean hastakeout = false;

    //送烟
    public void cigratee() {
        lock.lock();
        try {
            while (!hashcig) {
                try {
                    System.out.println("没有烟，歇一会");
                    // 前半段：释放锁，进入条件队列，然后阻塞线程；

                    // 过度阶段：被唤醒，被其他调用singal/singalAll的线程唤醒（前提：需要在同步队列中），被唤醒线程需要在同步队列中；
                    //调用singal/singalAll的线程：条件队列转同步队列；

                    // 后半段：获取所（CAS，如果有竞争，获取锁失败，还会阻塞），释放锁（唤醒同步队列中head的后续节点所在线程）；
                    // 标准的独占锁逻辑
                    cigCon.await();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            System.out.println("有烟了，干活");
        } finally {
            //唤醒同步队列里面的线程
            lock.unlock();
        }
    }

    //送外卖
    public void takeout() {
        lock.lock();
        try {
            while (!hastakeout) {
                try {
                    System.out.println("没有饭，歇一会");
                    takeCon.await();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            System.out.println("有饭了，干活");
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ReentrantLockDemo6 test = new ReentrantLockDemo6();
        new Thread(() -> {
            test.cigratee();
        }).start();

        new Thread(() -> {
            test.takeout();
        }).start();

        new Thread(() -> {
            lock.lock();
            try {
                hashcig = true;
                System.out.println("唤醒送烟的等待线程");
                cigCon.signal();
            } finally {
                lock.unlock();
            }


        }, "t1").start();

        new Thread(() -> {
            lock.lock();
            try {
                hastakeout = true;
                System.out.println("唤醒送饭的等待线程");
                takeCon.signal();
            } finally {
                lock.unlock();
            }


        }, "t2").start();
    }

}
